<template>
	<view class="container-shop">
	<scroll-view class="category-scroll" scroll-x enhanced show-scrollbar="false">
			<view class="" style="display: flex">
				<view class="category-all">
					<view class="category-item" @touchend.prevent="categoryAll">
						<view class="category-img-box">
							<image class="category-img" src="/static/cateall.png" mode="aspectFill"></image>
						</view>
						<view :class="['category-all-txt', selectedCategoryId === '' ? 'active' : '']">
							<text>全部分类</text>
						</view>
					</view>
				</view>
				<view class="category-item-wrapper" v-for="(category, index) in category" :key="category.id">
					<view class="category-item" @click="changeCategory(category.id)">
						<view class="category-img-box">
							<image class="category-img" :src="category.img.url" mode="aspectFill"></image>
						</view>
						<view :class="['category-txt', selectedCategoryId === category.id ? 'active' : '']">
							<text>{{ category.name }}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 3. 商品列表区域（修复固定定位，适配顶部分类） -->
		<view class="list-container">
			<view v-if="submenushow && selectedCategoryId !== ''" class="subCategory">
				<view
					class="subCategory-item"
					:class="{ active: subCategoryId === sub.id }"
					v-for="(sub, subIndex) in subCategory"
					:key="sub.id"
					@click="handleSubCategory(sub.id)"
				>
					<text class="subCategory-name-txt" :class="{ active: subCategoryId === sub.id }">{{ sub.name }}</text>
				</view>
			</view>
			<view v-if="selectedCategoryId === ''" class="subCategory">
				<view
					class="subCategory-item"
					:class="{ active: subCategorySeachId === sub.id }"
					v-for="(sub, subIndex) in subCategoryAll"
					:key="sub.id"
					@click="handleSubCategorySeachWord(sub.id, sub.name)"
				>
					<text class="subCategory-name-txt" :class="{ active: subCategorySeachId === sub.id }">{{ sub.name }}</text>
				</view>
			</view>
			<!-- 商品列表滚动容器 -->
			<scroll-view
				class="product-list"
				:style="{ height: `calc(100vh - ${navBarTop + navBarHeight}rpx)` }"
				scroll-y
				enhanced
				show-scrollbar="false"
				enable-back-to-top
				@scroll="handleScroll"
			>
				<!-- 列表模式（分类筛选） -->
				<view class="category-list-mode">
					<view v-for="(product, index) in computedProducts" :key="index" class="category-product-item">
						<!-- 商品信息 -->
						<view class="product-card">
							<view class="img-box">
								<image :src="product.images[0].url" class="product-img" @click.stop="navigateToDetail(product)"></image>
							</view>
							<view class="product-detail">
								<view class="product-name">
									{{ product.productName }}
								</view>
								<view class="description">
									{{ product.description }}
								</view>
								<view class="price-addcar">
									<view class="price">¥{{ (product.price || 0).toFixed(2) }}</view>
								</view>
							</view>

							<view class="quantity-container">
								<view class="left-buttons">
									<button v-if="getQuantity(product._id) > 0" class="quantity-btn minus" @touchend.prevent="changeQuantity(product, -1)">-</button>
									<text v-if="getQuantity(product._id) > 0" class="quantity">
										{{ getQuantity(product._id) }}
									</text>
								</view>
								<button class="quantity-btn plus" @touchend.prevent="changeQuantity(product, 1)">+</button>
							</view>
						</view>
					</view>
				</view>
				<uni-load-more :status="loadingStatus" class="load-more" />
			</scroll-view>
		</view>

		<!-- 购物车组件（非编辑模式显示） -->

		<view v-if="isEdit" class="addBtn" @click="addGood">
			<uni-icons type="compose" color="#fff" size="28"></uni-icons>
			<text>新品</text>
		</view>
	</view>
</template>

<script>
import shopNavbar from '@/components/shopNavbar.vue';


export default {
	components: { shopNavbar },
	props: {
		senderUserId: {
			type: String,
			default: ''
		},
		productList: {
			type: Array,
			default: () => []
		},
		category:{
			type:Array,
			default:()=>([])
		}
	},
	data() {
		return {
			userList: [],
			// category: [],
			selectedCategoryId: '', // 当前选中的大类ID（用id而非对象，避免引用问题）
			subCategoryId: '-1',
			subCategorySeachId: '-1', // 当前选中的小类ID（初始-1表示全部）
			isAdmin: false,

			submenushow: true,
			isEdit: false,
			loading: false, // 商品加载状态
			loadingStatus: 'more', // 加载更多状态：more/loading/noMore
			groupId: null,
			showup: true,
			navBarTop: 0, // 安全区域顶部距离
			navBarHeight: 120, // 导航栏高度（与shopNavbar一致）
			lastScrollTop: 0,
			shopName: '',
			scrollThreshold: 50,
			searchWord: '',
			subCategoryAll: [
				{
					id: '01',
					name: '推荐'
				},
				{
					id: '02',
					name: '最新'
				},
				{
					id: '03',
					name: '爆款'
				}
			],
			isIos: false // 是否为iOS设备（用于底部安全区域适配）
		};
	},
	computed: {
		// 当前选中的大类（用于关联小类）
		currentCategory() {
			const sub = this.category.find((item) => item.id === this.selectedCategoryId) || {};
			if (Object.keys(sub).length > 0) {
				return sub;
			} else {
				return {};
			}
		},
		subCategory() {
			if (this.selectedCategoryId === '') {
				// 修复：全部分类时，返回空数组（避免小类列表渲染错误）
				return [];
			}
			// 容错：当前大类不存在时，返回空数组
			return this.currentCategory?.subCategory || [];
		},

		computedProducts() {
			return this.productList.filter((item) => {
				// 首先判断大类是否匹配
				const isCategoryMatch = this.selectedCategoryId === '' ? true : item.categorize === this.selectedCategoryId;
				const seachWord = this.searchWord === '' ? true : item.tag === this.searchWord;
				// 如果小类是-1，则只需要大类匹配；否则需要小类也匹配
				const isSubCategoryMatch = this.subCategoryId === '-1' ? true : item.subCategorize === this.subCategoryId;
				const sendUserId = this.senderUserId === '' ? true : this.senderUserId === item.senderUserId;

				return isCategoryMatch && isSubCategoryMatch && sendUserId && seachWord;
			});
		}
	},

	mounted() {
		// 1. 提前缓存屏幕宽度（用于rpx转换），避免滚动时频繁调用
		try {
			const res = this.$store.state.msg.systemInfo;
			this.navBarTop = res.safeArea.top * (750 / res.windowWidth);
			this.isIos = res.system.toLowerCase().includes('ios');
			this.screenWidth = res.windowWidth; // 缓存屏幕宽度，后续滚动时复用
		} catch (e) {
			console.error('获取设备信息失败：', e);
			this.screenWidth = 375; // 异常时默认宽度（iPhone 6/7/8）
		}
		//   this.initData()
		//this.getCategory();
		//this.getSendShop();
		// 2. 监听搜索结果事件（原有逻辑保留）
	
	},


	methods: {


		getQuantity(productId) {
			const items = this.$store?.state?.cart?.items || [];
			const item = items.find((item) => item._id === productId);
			return item?.quantity || 0;
		},
		categoryAll() {
			this.subCategoryId = '-1';
			this.selectedCategoryId = '';
			this.subCategorySeachId = '-1'; // 新增：重置搜索分类选中
			this.searchWord = ''; // 新增：重置搜索词
		},
	
		// 滚动控制导航栏显隐
		handleScroll(e) {
			const currentScrollTop = e.detail.scrollTop;
			const currentScrollTopRpx = currentScrollTop * (750 / this.screenWidth);

			// 向上滚动：超过20rpx差值且未隐藏标题区，才触发隐藏
			if (currentScrollTopRpx - this.lastScrollTop > 35) {
				if (currentScrollTopRpx > this.scrollThreshold && this.showup) {
					this.showup = false;
					this.navBarHeight = 90; // 导航栏高度从120→90
				}
			}
			// 向下滚动：超过20rpx差值且已隐藏标题区，才触发显示
			else if (this.lastScrollTop - currentScrollTopRpx > 35) {
				if (!this.showup) {
					this.showup = true;
					this.navBarHeight = 120; // 导航栏高度从90→120
				}
			}

			this.lastScrollTop = currentScrollTopRpx;
		},
		handleSubCategorySeachWord(id, word) {
		
			this.subCategorySeachId = id;
			this.searchWord = word;
		},

		// 增减购物车数量
		changeQuantity(item, delta) {
			uni.vibrateShort({});
			const currentQty = this.getQuantity(item._id);

			if (currentQty === 0) {
				// 新增商品到购物车
				this.$store.commit('cart/addItem', { ...item, quantity: 1 });
			} else {
				const newQty = currentQty + delta;
				if (newQty > 0) {
					// 更新数量
					this.$store.commit('cart/updateQuantity', {
						id: item._id,
						quantity: newQty
					});
				} else {
					// 移除商品
					this.$store.commit('cart/removeItem', item._id);
				}
			}
		},

		// 分享商品
		toShare(product) {
			const formatedProduct = encodeURIComponent(JSON.stringify(product));
			uni.navigateTo({
				url: `/pages/shareGood/shareGood?product=${formatedProduct}`
			});
		},

		// 新增商品
		addGood() {
			uni.navigateTo({
				url: `/pages/sendGood/sendGood?groupId=${this.groupId}`
			});
		},

		// 生成商品卡片
		cardshow(product) {
			const formatedProduct = encodeURIComponent(JSON.stringify(product));
			uni.navigateTo({
				url: `/pages/sendGoodCard/sendGoodCard?cardInfo=${formatedProduct}`
			});
		},

		// 管理员模式切换

		// 编辑商品（传入当前商品ID，避免跳转到空页面）
		editgood(product) {
			uni.navigateTo({
				url: `/pages/saleGood/saleGood?productId=${product.productId}`
			});
		},

		// 小类切换
		handleSubCategory(id) {
			this.searchWord = '';
			this.subCategoryId = id;
		},

		// 大类切换
		changeCategory(categoryId) {
			this.selectedCategoryId = categoryId;
			this.searchWord = '';
			this.subCategoryId = '-1';
			this.subCategorySeachId = '-1'; // 新增：重置搜索分类选中
		},

		// 跳转到搜索页
		handleSearch() {
			uni.navigateTo({
				url: `/pages/searchGood/searchGood?groupId=${this.groupId}`
			});
		},

		// 添加到购物车
		addToCart(product) {
			this.$store.commit('cart/addItem', { ...product, quantity: 1 });
			uni.vibrateShort();
			uni.showToast({ title: '已加入购物车', icon: 'success' });
		},

		// 跳转到商品详情
		navigateToDetail(product) {
			const formated = encodeURIComponent(JSON.stringify(product));
			uni.navigateTo({
				url: `/pages/goodDetail/goodDetail?product=${formated}`
			});
		},


		// 构建商品查询条件（复用逻辑，避免重复代码）
		buildQuery() {
			const query = { groupId: this.groupId };

			// 大类筛选（选中时）
			if (this.selectedCategoryId !== null && this.selectedCategoryId !== undefined) {
				query.categorize = Number(this.selectedCategoryId); // 确保类型为数字
			}

			// 小类筛选（选中时）
			if (this.subCategoryId > 0) {
				query.subCategorize = Number(this.subCategoryId); // 确保类型为数字
			}

			return query;
		},

		// 促销标签样式（容错：避免无对应tag时样式错误）
		tagStyle(tag) {
			const styleMap = {
				限时折扣: { background: '#e64340' },
				新品上市: { background: '#07c160' },
				爆款热卖: { background: '#ff976a' },
				限时优惠: { background: '#ff3d00' },
				新品: { background: '#007aff' } // 补充常见tag样式
			};
			return styleMap[tag] || { display: 'none' };
		}
	}
};
</script>

<style lang="scss" scoped>
/* 基础容器：移除固定margin-top，用动态padding适配顶部 */
.container-shop {
	position: fixed;
	top: 280rpx;
	left: 0;
	right: 0;
	bottom: 0; // 修复：设置底部为0，占满全屏
	//padding-bottom: 120rpx;
	overflow: hidden; // 避免内部元素溢出
}

/* 1. 大类横向滚动容器 */
.category-scroll {
	white-space: nowrap;
	margin: 10rpx 0rpx;
	padding: 15rpx 20rpx;
	background: #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); /* 增加阴影区分层级 */
}
.category-img-box {
	border-radius: 20rpx;
	border: 3rpx solid #ccc; /* 合并写法：宽度 + 样式 + 颜色 */
	border-color: #ccc;
	padding: 5rpx 5rpx;
}
.category-img {
	width: 80rpx;
	height: 80rpx;
	border-radius: 20rpx;
}
.category-item-wrapper {
	display: inline-block;
	margin-right: 20rpx; /* 调整间距，避免过宽 */
}
.category-all {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	font-weight: bold;
	color: #666;
	transition: all 0.2s ease;
}
.category-all-txt {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 30rpx;
	padding: 5rpx 0;
	width: 120rpx;
	border-radius: 15rpx;
	&.active {
		background: #e64340;
		color: #fff;
		font-weight: 500;
	}
}
.category-item {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	font-weight: bold;
	color: #666;
	transition: all 0.2s ease;
	.category-txt {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 30rpx;
		padding: 5rpx 10rpx;
		border-radius: 15rpx;

		&.active {
			background: #e64340;
			color: #fff;
			font-weight: 500;
		}
	}
}

/* 2. 小类纵向列表 */
.subCategory {
	flex-shrink: 0; /* 固定宽度，不被压缩 */
	width: 160rpx;

	background-color: #55aaff;
	/* 关键：高度固定为屏幕高度减去顶部区域，与商品列表高度一致 */
	height: calc(100vh-#{navBarTop});
	overflow-y: auto; /* 小类过多时，自身内部滚动 */
	/* 避免小类容器随外部滚动 */
	position: sticky;
	top: 0; /* 相对于父容器（list-container）顶部固定 */
}
.subCategory-name-txt {
	color: #fff;
	font-weight: 500;
}
.active {
	color: #55aa00;
	font-weight: 600;
}
.subCategory-item {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 10rpx 15rpx; /* 调整内边距，增加点击区域 */
	height: 60rpx;
	font-size: 26rpx;
	color: #333;
	text-align: center;
	transition: all 0.2s ease;

	&.active {
		background-color: #fff;
		color: #55aa00;
		font-weight: 600;
		border-left: 10rpx solid #55aa00;
	}
}

/* 3. 商品列表容器：用padding-top适配顶部分类，避免固定定位 */
.list-container {
	padding-bottom: 20rpx;
	display: flex; /* 保留flex，但用于实现“小类左、列表右”的并列布局 */
	background-color: #fff; /* 改为白色，与商品卡片背景一致 */
}
.product-detail {
}
/* 无商品提示 */
.none {
	width: 100%;
	padding: 100rpx 0;
	text-align: center;
	color: #ccc;
	font-size: 28rpx;
	background-color: white;
	margin: 20rpx;
	border-radius: 16rpx;
}

/* 商品列表滚动容器 */
.product-list {
	flex: 1; /* 占满右侧剩余宽度 */
	/* 关键：高度固定为屏幕高度减去顶部区域，确保能独立滚动 */
	height: 100vh;
	overflow-y: auto; /* 仅商品列表滚动 */
	padding: 10rpx;
}

/* 网格模式 */
.product-grid {
	display: flex;
	flex-wrap: wrap;
	padding: 10rpx;
	justify-content: space-between;
}

.product-card {
	background: #fff;
	display: flex;
	flex: 1;
	gap: 20rpx;
	padding: 10rpx 20rpx;
	overflow: hidden;
	position: relative;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	transition: transform 0.2s ease;

	&:active {
		transform: scale(0.98); /* 点击反馈 */
	}
}

.product-image {
	width: 100%;
	height: 100%;
	border-radius: 10rpx; /* 调整图片高度，避免过高 */
}

/* 管理员操作：商品管理 */
.editgood {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.6);
	color: #fff;
	font-size: 28rpx;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 2;
}

/* 管理员操作：分享+卡片 */
.admin-actions {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	z-index: 2;
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.redo,
.cardshow {
	background-color: rgba(255, 255, 255, 0.8);
	border-radius: 8rpx;
	padding: 8rpx;
	font-size: 20rpx;
	color: #007aff;
	text-align: center;
}

/* 商品信息 */
.product-info {
	padding: 16rpx;
}

.product-title {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	margin-bottom: 8rpx;
}

.description {
	font-size: 24rpx;
	color: #999;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1; /* 描述只显示1行 */
	overflow: hidden;
	margin-bottom: 12rpx;
}

.price-section {
	margin-bottom: 12rpx;
	display: flex;
	align-items: baseline;
}

.current-price {
	color: #e64340;
	font-size: 30rpx;
	font-weight: 500;
}

.original-price {
	color: #999;
	font-size: 22rpx;
	text-decoration: line-through;
	margin-left: 12rpx;
}

.sales-tag {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 22rpx;
	color: #999;
}

/* 促销标签 */
.product-tag {
	position: absolute;
	top: 10rpx;
	left: 0;
	padding: 6rpx 20rpx;
	color: #fff;
	font-size: 22rpx;
	border-radius: 0 20rpx 20rpx 0;
	z-index: 1;
}

/* 列表模式 */
.category-list-mode {
	padding-bottom: 200rpx;
}

.category-product-item {
	display: flex;

	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 10rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.img-box {
	width: 200rpx;
	height: 200rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box; /* 关键：让宽高包含内边距，确保容器总尺寸为200rpx */
}

.product-img {
	width: 200rpx;
	height: 200rpx;
	border-radius: 8rpx;
	object-fit: cover; /* 新增：保持图片比例，裁剪多余部分（避免拉伸） */
	display: block; /* 消除图片底部可能出现的空白间隙 */
}

.product-name {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	margin-bottom: 8rpx;
}

.price-addcar {
	display: flex;
	align-items: center;
	margin-top: auto; /* 推到底部 */
	justify-content: space-between;
}

.price {
	font-size: 30rpx;
	font-weight: 500;
	color: #e64340;
}
/* 购物车数量控制 */
.quantity-container {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8rpx;
	position: absolute;
	bottom: 20rpx;
	right: 20rpx;
	z-index: 999;
	.left-buttons {
		display: flex;
		align-items: center;
		gap: 8rpx; /* 减号和数量文本的间距 */
	}
}

.quantity-btn {
	width: 44rpx;
	height: 44rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 32rpx;
	padding: 0;
	line-height: 1; /* 修复按钮文字居中 */
}

.minus {
	background-color: #f5f5f5;
	color: #666;
}

.plus {
	background-color: #e64340;
}

.quantity {
	font-size: 26rpx;
	color: #333;
	width: 40rpx;
	text-align: center;
}

/* 新增商品按钮 */
.addBtn {
	position: fixed;
	right: 30rpx;
	bottom: 150rpx; /* 适配购物车高度 */
	width: 120rpx;
	height: 120rpx;
	color: #fff;
	background-color: #e64340;
	border-radius: 60rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(230, 67, 64, 0.4);
	z-index: 98;
}

/* 加载更多样式 */
.load-more {
	padding: 30rpx 0;
	text-align: center;
}

/* 适配iOS底部安全区域 */
@media (prefers-bottom-safe-area-inset: 34rpx) {
	.shopCar {
		padding-bottom: 34rpx !important;
	}
}
</style>